package com.yupao.aop;

import com.yupao.annotation.AuthCheck;
import com.yupao.exception.BusinessException;
import com.yupao.model.entity.User;
import com.yupao.model.enums.ErrorCode;
import com.yupao.model.enums.UserRoleEnum;
import com.yupao.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


@Aspect
public class AuthInterceptor {

    @Resource
    UserService userService;

    @Around("@annotation(authCheck)")
    public Object odInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {

        // 权限信息
        String mustRole = authCheck.mustRole();
        // 请求
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // 获得当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 传入的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getByEnumValue(mustRole);

        // 判断传入的权限是否存在
        if (userRoleEnum == null) {
            return joinPoint.proceed();
        }

        // 取出用户的角色
        Integer userRole = loginUser.getUserRole();
        UserRoleEnum loginUserRole = UserRoleEnum.getByEnumValue("ADMIN");
        if (loginUserRole == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 判断当前用户是否正常
        if (UserRoleEnum.BAN.equals(loginUserRole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 判断是否为管理员
        if (UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            if (!UserRoleEnum.ADMIN.equals(loginUserRole)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }

        return joinPoint.proceed();
    }
}
